<?php


namespace app\common\service;

use app\common\exception\BaseException;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;

class GeocodeService
{
    // 配置
    protected mixed $config;

    // 实例化
    public static ?GeocodeService $_instance = null;

    public static function instance(): ?GeocodeService
    {
        if (!static::$_instance) static::$_instance = new static();
        return static::$_instance;
    }

    // 设置初始配置
    public function setConfig(array $config = []): GeocodeService
    {
        $this->config = $config;
        return $this;
    }

    /**
     * @throws BaseException
     */
    public function gd_geocode($address): array
    {
        try {
            $client = new Client();
            $response = $client->get($this->config['gd_url'] . "?key=" . $this->config['gd_key'] . "&address=" . $address);
            $statusCode = $response->getStatusCode();
            if ($statusCode == 200) {
                $body = $response->getBody()->getContents();
                $data = json_decode($body, true);
                if ($data['status'] == '1' && isset($data['geocodes'][0])) {
                    $data = $data['geocodes'][0];
                    $location = explode(',', $data['location']);
                    $lon = $location[0];
                    $lat = $location[1];
                    return compact('lon', 'lat');
                } else {
                    throw new BaseException(['message' => '']);
                }
            } else {
                // 错误处理逻辑
                throw new BaseException(['message' => '']);
            }
        } catch (GuzzleException $e) {
            throw new BaseException(['message' => '连接失败' . $e->getMessage()]);
        }
    }

}